<?php
define('DEFAULT_CON','index');
define('DEFAULT_ACT','default');
class myrequest {
	public static $inputJson;
	public static function getInput(){
		return file_get_contents('php://input');
	}

	public static function isWhiteDomain($url){
		$mainDomain = get_main_domain($url);
		if(in_array($mainDomain,white_domain())){
			return true;
		}
		return false;
	}

	public static function getJson(){
		if(!self::$inputJson) {
			self::$inputJson = json_decode(self::getInput());
		}
		return self::$inputJson;
	}

	public static function getFrom(){
		$reg = "/(http[s]?:\/\/.*?)\//i";
		if ($_SERVER['HTTP_REFERER'])
		{
			$src = $_SERVER['HTTP_REFERER'];
			preg_match($reg, $src, $match);
			$httpUrl = $match[1];
		}
		else
		{
			$httpUrl = $_SERVER['HTTP_ORIGIN'];
		}
		return $httpUrl;
	}

	public static  function isHttps() {
		if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
			return TRUE;
		} elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
			return TRUE;
		} elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
			return TRUE;
		}
		return FALSE;
	}

    /**
     * 获取当前url地址
     * @return String 当前URL
     * */
    public static function getUrl($isFull=true){
        if(!$isFull){
            return  $_SERVER['REQUEST_URI'];
        }else{
            if(self::isHttps()){
                return 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            }else{
                return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            }
        }
    }


    /**
	 * 获取域名的首页链接
	 * */
	public static function getDomainUrl($url=''){
		if(!$url){//没有设定url
			$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
			return $http_type.$_SERVER['HTTP_HOST'].'/';
		}else{
			$urlInfo = parse_url($url);
			return $urlInfo['scheme'].'://'.$urlInfo['host'].'/';
		}
	}

	public static function getBaseUrl($url=''){
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

		if(!$url) $url = $http_type.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
		$main = self::getDomainUrl($url);
		$path = self::getDir($url);
		return $main.$path.'/';
	}

	public static function getPath($url){
		$urlInfo = parse_url($url);
		return $urlInfo['path'];
	}


	public static function getDir($url){
		$path = self::getPath($url);
		preg_match("/(.*\/)/i",$path,$match);
		return $match[1];
	}


    /**
	 * 获取域名的首页链接
	 * */
	public static function getHttpUrl($url=''){
		return self::getDomainUrl($url);
	}

	/**
	 * 获取域名
	 * */
	public static function getDomain($url=''){
		if(!$url){
			return $_SERVER['HTTP_HOST'];
		}

		$urlInfo = parse_url($url);
		return $urlInfo['host'];
	}
    
    //获取主域名
    public static function getMainDomain($url =''){
        if(!$url) $url = $_SERVER['HTTP_HOST'];
        $host = strtolower ( $url ); 
        if (strpos ( $host, '/' ) !== false) { 
        $parse = @parse_url ( $host ); 
        $host = $parse ['host']; 
        } 
        $topleveldomaindb = array ('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me' ,'xin','io','tv'); 
        $str = ''; 
        foreach ( $topleveldomaindb as $v ) { 
        $str .= ($str ? '|' : '') . $v; 
        } 

        $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$"; 
        if (preg_match ( "/" . $matchstr . "/ies", $host, $matchs )) { 
        $domain = $matchs ['0']; 
        } else { 
        $domain = $host; 
        } 
        return $domain; 
    }

	public function __construct(){
		$this->parse();
	}

	public  function g($getVar,$default = null){
		if('con' == $getVar){
			if(!isset($_GET[$getVar])){
				return DEFAULT_CON;//默认控制器为
			}
		}else if('act' == $getVar){
			if(!isset($_GET[$getVar])){
				return DEFAULT_ACT;//默认控制器为
			}
		}

		if(isset($_GET[$getVar])){
			return self::encode(self::decode($_GET[$getVar]));
		}elseif(isset($this->$getVar)){
			return $this->$getVar;
		}else {
			return $default;
		}
	}

	public function s($varname){
		global $myParsedParams;
		if(in_array($varname,$myParsedParams)) return true;
		if(isset($_GET[$varname])) return true;
		if(isset($_POST[$varname])) return true;

		$json = self::getJson();
		if($json && property_exists($json,$varname)){
			return true;
		}
		return false;
	}

	public static  function p($postVar){
		if(isset($_POST[$postVar])){
			return  self::encode(self::decode($_POST[$postVar]));
		}else {
			return false;
		}
	}

	public static  function c($cookieVar){
		if(isset($_COOKIE[$cookieVar])){
			return  self::encode(self::decode($_COOKIE[$cookieVar]));
		}else {
			return false;
		}
	}


	public static function encode($str){
        if(is_array($str))
        {
            return $str;
        }
		return addslashes(str_replace('`','',$str));
	}

	public static function decode($str){
	    if(is_array($str))
        {
            return $str;
        }
		return stripslashes($str);
	}

	public function r($requestVar){
		$json = self::getJson();
		if($json && property_exists($json,$requestVar)){
			return $json->$requestVar;
		}else{
			$p = p($requestVar);
			if($p!=''){
				return $p;
			}else {
				return g($requestVar);
			}
		}
	}

	/**
	 * 解析url
	 * 
	 * */
	public function parse(){
		global $myParsedParams;
		if(!is_array($myParsedParams)) $myParsedParams = [];
		$paramstr = preg_replace ('/\/+/','',$_GET['param']);
		$paramstr = preg_replace("/\.html$/",'',$paramstr);

		$params = explode(',',$paramstr);
		for($i = 0; $i < count($params); $i +=2){
			$tmpKey = $params[$i];
			if(!$tmpKey) continue;
			if(!in_array($tmpKey,$myParsedParams)){
				$myParsedParams[] = $tmpKey;
			}

			if(isset($params[$i+1])){
				$this->$tmpKey = addslashes(htmlspecialchars($params[$i+1]));
			}else{
				$this->$tmpKey = '';
			}
		}
	}


	/**
	 * 获取ip
	 * */
	public static function  getIP(){
		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$realip = $_SERVER['HTTP_X_FORWARDED_FOR'];//代理服务器的IP
			} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$realip = $_SERVER['HTTP_CLIENT_IP'];//客户端IP
			} else {
				$realip = $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的IP
			}
		} else {
			if (getenv("HTTP_X_FORWARDED_FOR")) {
				$realip = getenv( "HTTP_X_FORWARDED_FOR");
			} elseif (getenv("HTTP_CLIENT_IP")) {
				$realip = getenv("HTTP_CLIENT_IP");
			} else {
				$realip = getenv("REMOTE_ADDR");
			}
		}
		return $realip;
	}

	/**
	 * 获取Agent
	 * */
	public static function getAgent(){
		return $_SERVER['HTTP_USER_AGENT'];
	}
	
	public static function getBrowser(){
		return self::getAgent();
	}

	/**
	 * 获取来源
	 * */
	public static function getReferer(){
		if(isset($_SERVER['HTTP_REFERER'])){
			return $_SERVER['HTTP_REFERER'];
		}else {
			return '';
		}
	}



	/**
	 * 判断是否为POST方式提交的数据
	 * */
	public static function isPost(){
		if(sizeof($_POST)>0){
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 获取$_SERVER['PHP_SELF']，防止跨域攻击
	 * @return 获取$_SERVER['PHP_SELF']，防止跨域攻击 
	 * */
	public static function getPhpSelf(){
		return self::encode($_SERVER['PHP_SELF']);
	}
}